/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        queue<TreeNode*> que;
        if (root) que.push(root);

        vector<vector<int>> result;
        int flag = 0;

        while (!que.empty()) {
            int count = que.size();
            vector<int> tmp;

            for (int i = 0; i < count; i++) {
                TreeNode* node = que.front();
                tmp.push_back(node->val);

                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
                que.pop();
            }

            if (flag % 2) {
                reverse(tmp.begin(), tmp.end());
            }
            result.push_back(move(tmp));
            flag++;
        }
        return result;
    }
};
